import re

from flask import Blueprint, g, jsonify
from mongoengine import Q

from .operation_trajectory_model import OperationTrajectory

operation_trajectory_bp = Blueprint('operation_trajectory_bp', __name__)


@operation_trajectory_bp.route('/all')
def all():
    project_id = g.params.get('project_id')
    key = g.params.get('key')
    if project_id:
        operation_trajectorys = OperationTrajectory.objects(project=project_id)
    else:
        operation_trajectorys = OperationTrajectory.objects
    if key:
        key = re.compile(key)
        operation_trajectorys = operation_trajectorys.filter(
            Q(opetation_user=key) | Q(page=key) | Q(detail=key) | Q(ip=key))
    total = operation_trajectorys.count()
    operation_trajectorys = operation_trajectorys.order_by('-operation_time').skip(
        (g.params.get('page', 1) - 1) * g.params.get('page_size', 20)).limit(g.params.get('page_size', 20))
    return jsonify(data=[operation_trajectory.to_json() for operation_trajectory in operation_trajectorys], msg='成功', code=0, total=total)
